/**
 * 
 */
package junior.util.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP格式压缩与解压（GZIP只能对单文件压缩）
 * @author WuBo
 * @CreateDate 2013-11-19 上午11:29:36
 */
public class GZIPUtils {
	/**
	 * GZIP压缩文件
	 * @param file 原文件
	 * @param gzipFile Gzip压缩文件
	 * @param delAfterCompressed 是否压缩后删除原文件
	 * @return 返回解压前的文件大小
	 * @throws Exception
	 */
	public static void gzip(File file, File gzipFile, boolean delAfterCompressed) throws Exception {
		gzip(new FileInputStream(file), new FileOutputStream(gzipFile));
		if(delAfterCompressed){
			FileUtils.delete(file);
		}
	}
	/**
	 * GZIP压缩文件
	 * @param is
	 * @param os
	 * @return 返回解压前的文件大小
	 * @throws Exception
	 */
	public static long gzip(InputStream is, OutputStream os) throws Exception {
		BufferedInputStream bis = null;
		GZIPOutputStream gos = null;
		long total = 0;
		bis = new BufferedInputStream(is);
		gos = new GZIPOutputStream(new BufferedOutputStream(os));
		byte[] data = new byte[10240];
		int len = 0;
		while((len = bis.read(data)) != -1){
			total += len;
			gos.write(data, 0, len);
		}
		gos.flush();
        gos.finish();
		return total;
	}

	/**
	 * GZIP解压缩
	 * @param gzipFile 压缩文件
	 * @param file 解压后文件
	 * @param delAfterDecompressed 是否解压后删除原文件
	 * @return 返回解压后的文件大小
	 * @throws Exception
	 */
	public static long ungzip(File gzipFile, File file, boolean delAfterDecompressed) throws Exception {
		long len = ungzip(new FileInputStream(gzipFile), new FileOutputStream(file));
		if(delAfterDecompressed){
			FileUtils.delete(gzipFile);
		}
		return len;
	}
	/**
	 * GZIP解压缩
	 * @param is
	 * @param os
	 * @return 返回解压后的文件大小
	 * @throws Exception
	 */
	public static long ungzip(InputStream is, OutputStream os) throws Exception {
		GZIPInputStream gis = null;
		BufferedOutputStream bos = null;
		long total = 0;
		gis = new GZIPInputStream(new BufferedInputStream(is));
		bos = new BufferedOutputStream(os);
		byte[] data = new byte[10240];
		int len = 0;
		while((len = gis.read(data)) != -1){
			total += len;
			bos.write(data, 0, len);
		}
		bos.flush();
		return total;
	}
	
}
